<template>
  <div class="app-container">
    <PlatformHeader />
    <el-row :gutter="20" style="height: calc(100vh - 72px);padding-top: 10px;padding-bottom: 10px">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!-- 部门数据 -->
        <pane size="10" class="left-pane">
          <div class="head-container">
            <el-input
              v-model="deptName"
              placeholder="请输入部门名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              class="dept-search custom-height-input"
            />
          </div>
          <div class="head-container tree-container" style="height: calc(100vh - 134px);overflow: auto">
            <el-tree
              :data="deptOptions"
              :props="defaultProps"
              :expand-on-click-node="true"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="id"
              :default-expand-all="false"
              highlight-current
              @node-click="handleNodeClick"
              class="custom-tree"
            />
          </div>
        </pane>

        <!-- 监测点数据 -->
        <pane size="90" class="right-pane">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="90px"
            class="search-form custom-form"
          >
<!--            <el-form-item label="" prop="year">-->
<!--              <el-select-->
<!--                popper-class="custom-select-dropdown"-->
<!--                style="width: 110px"-->
<!--                v-model="queryParams.year"-->
<!--                placeholder="选择年份"-->
<!--                clearable-->
<!--                filterable-->
<!--                class="year-select"-->
<!--                @keyup.enter.native="handleQuery"-->
<!--              >-->
<!--                <el-option-->
<!--                  v-for="item in yearOptions"-->
<!--                  :key="item"-->
<!--                  :label="item"-->
<!--                  :value="item"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--            <el-form-item>-->
<!--              <el-button-->
<!--                type="primary"-->
<!--                icon="el-icon-search"-->
<!--                size="mini"-->
<!--                @click="handleQuery"-->
<!--                class="search-btn action-btn"-->
<!--              >-->
<!--                搜索-->
<!--              </el-button>-->
<!--              <el-button-->
<!--                icon="el-icon-refresh"-->
<!--                size="mini"-->
<!--                @click="resetQuery"-->
<!--                class="reset-btn action-btn"-->
<!--              >-->
<!--                重置-->
<!--              </el-button>-->
<!--              <el-button-->
<!--                type="primary"-->
<!--                plain-->
<!--                icon="el-icon-plus"-->
<!--                size="mini"-->
<!--                @click="handleAdd"-->
<!--                class="add-btn action-btn"-->
<!--                v-hasPermi="['monitormanage:testpoint:add']"-->
<!--              >-->
<!--                新增-->
<!--              </el-button>-->
<!--              <el-button-->
<!--                type="success"-->
<!--                plain-->
<!--                icon="el-icon-edit"-->
<!--                size="mini"-->
<!--                :disabled="single"-->
<!--                @click="handleUpdate"-->
<!--                v-hasPermi="['monitormanage:testpoint:edit']"-->
<!--                class="edit-btn action-btn"-->
<!--              >-->
<!--                修改-->
<!--              </el-button>-->
<!--              <el-button-->
<!--                type="danger"-->
<!--                plain-->
<!--                icon="el-icon-delete"-->
<!--                size="mini"-->
<!--                :disabled="multiple"-->
<!--                @click="handleDelete"-->
<!--                v-hasPermi="['monitormanage:testpoint:remove']"-->
<!--                class="delete-btn action-btn"-->
<!--              >-->
<!--                删除-->
<!--              </el-button>-->
<!--              <el-button-->
<!--                type="warning"-->
<!--                plain-->
<!--                icon="el-icon-download"-->
<!--                size="mini"-->
<!--                @click="handleExport"-->
<!--                v-hasPermi="['monitormanage:testpoint:export']"-->
<!--                class="export-btn action-btn"-->
<!--              >-->
<!--                导出-->
<!--              </el-button>-->
<!--              <el-button-->
<!--                type="warning"-->
<!--                plain-->
<!--                icon="el-icon-upload"-->
<!--                size="mini"-->
<!--                @click="handleImport"-->
<!--                v-hasPermi="['monitormanage:testpoint:export']"-->
<!--                class="import-btn action-btn"-->
<!--              >-->
<!--                导入上一年度监测点-->
<!--              </el-button>-->
<!--            </el-form-item>-->
          </el-form>

          <!--          <div class="el-form-item">-->
          <!--            <el-button-->
          <!--              type="primary"-->
          <!--              plain-->
          <!--              icon="el-icon-plus"-->
          <!--              size="mini"-->
          <!--              @click="handleAdd"-->
          <!--              class="add-btn action-btn"-->
          <!--              v-hasPermi="['monitormanage:testpoint:add']"-->
          <!--            >-->
          <!--              新增-->
          <!--            </el-button>-->
          <!--            <el-button-->
          <!--              type="success"-->
          <!--              plain-->
          <!--              icon="el-icon-edit"-->
          <!--              size="mini"-->
          <!--              :disabled="single"-->
          <!--              @click="handleUpdate"-->
          <!--              v-hasPermi="['monitormanage:testpoint:edit']"-->
          <!--              class="edit-btn action-btn"-->
          <!--            >-->
          <!--              修改-->
          <!--            </el-button>-->
          <!--            <el-button-->
          <!--              type="danger"-->
          <!--              plain-->
          <!--              icon="el-icon-delete"-->
          <!--              size="mini"-->
          <!--              :disabled="multiple"-->
          <!--              @click="handleDelete"-->
          <!--              v-hasPermi="['monitormanage:testpoint:remove']"-->
          <!--              class="delete-btn action-btn"-->
          <!--            >-->
          <!--              删除-->
          <!--            </el-button>-->
          <!--            <el-button-->
          <!--              type="warning"-->
          <!--              plain-->
          <!--              icon="el-icon-download"-->
          <!--              size="mini"-->
          <!--              @click="handleExport"-->
          <!--              v-hasPermi="['monitormanage:testpoint:export']"-->
          <!--              class="export-btn action-btn"-->
          <!--            >-->
          <!--              导出-->
          <!--            </el-button>-->
          <!--            <el-button-->
          <!--              type="warning"-->
          <!--              plain-->
          <!--              icon="el-icon-upload"-->
          <!--              size="mini"-->
          <!--              @click="handleImport"-->
          <!--              v-hasPermi="['monitormanage:testpoint:export']"-->
          <!--              class="import-btn action-btn"-->
          <!--            >-->
          <!--              导入上一年度监测点-->
          <!--            </el-button>-->
          <!--          </div>-->

          <el-table
            v-loading="loadingone"
            :data="testpointList"
            @selection-change="handleSelectionChange"
            class="custom-table"
          >
<!--            <el-table-column type="selection" width="60" align="center" />-->
            <el-table-column label="测试年份"  width="120" align="center" prop="year"/>
            <el-table-column label="机构名称" align="center" prop="name" :show-overflow-tooltip="true"/>
            <el-table-column label="机构代码" align="center" prop="organizationcode" :show-overflow-tooltip="true"/>
            <el-table-column label="GPS坐标" align="center" prop="gps" :show-overflow-tooltip="true"/>
            <el-table-column label="联系人" align="center" prop="contactPerson"/>
            <el-table-column label="联系电话" align="center" prop="contactTel" width="180" :show-overflow-tooltip="true"/>
            <el-table-column label="状态" align="center" prop="type">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.sys_normal_disablev" :value="scope.row.type"/>
<!--               {{ scope.row.type === '100' ? '在线' : '离线' }}-->
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px;">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-video-camera"
                  @click="view(scope.row.organizationcode, scope.row.type, scope.row.name)"
                  v-hasPermi="['monitormanage:testpoint:edit']"
                  class="table-action-btn edit-btn"
                >
                  {{ viewingClient === scope.row.organizationcode ? '查看中...' : '查看监控' }}
                </el-button>
                <!--                <el-button
                                  size="mini"
                                  type="text"
                                  icon="el-icon-delete"
                                  @click="handleDelete(scope.row)"
                                  v-hasPermi="['monitormanage:testpoint:remove']"
                                  class="table-action-btn delete-btn"
                                >
                                  删除
                                </el-button>-->
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
            class="custom-pagination"
          />
        </pane>
      </splitpanes>
    </el-row>

    <!-- 添加或修改对话框  custom-class="custom-dialog"-->
    <!-- 视频查看弹窗:title="'实时监控 - ' + (viewingClient || '设备')" -->
    <el-dialog
      custom-class="custom-dialog"
      :title="'实时监控 - ' + viewingClientName + ' - ' + (viewingClient || '设备')"
      :visible.sync="videoDialogVisible"
      width="1200px"
      :before-close="handleVideoClose"
      @opened="onVideoDialogOpen"
      destroy-on-close
    >
      <div class="video-container">
        <video
          ref="remoteVideo"
          autoplay
          playsinline
          controls
          class="video-element"
          @click="togglePlay"
        ></video>

        <div class="audio-controls" v-if="hasVideo">
          <el-button
            :icon="isMuted ? 'el-icon-turn-off-microphone' : 'el-icon-microphone'"
            @click="toggleMute"
            circle
            class="audio-btn"
            :type="isMuted ? 'danger' : 'success'"
          >
            {{ isMuted ? '取消静音' : '静音' }}
          </el-button>
          <el-slider
            v-model="volume"
            :min="0"
            :max="100"
            @input="changeVolume"
            style="width: 100px; margin-left: 10px;"
            class="volume-slider"
          ></el-slider>
        </div>
      </div>

      <template #footer>
    <span class="dialog-footer">
      <el-button @click="takeSnapshot" :disabled="!hasVideo" class="add-btn action-btn">
        截图
      </el-button>
      <el-button @click="toggleFullscreen" class="edit-btn action-btn">
        全屏
      </el-button>
      <el-button type="primary" @click="stopView" class="dialog-btn confirm-btn dialog-confirm-btn">
        确认关闭
      </el-button>
    </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listTestpoint, getTestpoint, delTestpoint, addTestpoint, updateTestpoint, importold, getyears } from "@/api/monitormanage/testpoint";
import {deptTreeSelect, getUserProfile} from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { getOrg } from "../../../api/system/dept";
import PlatformHeader from '../../../components/PlatformHeader/index.vue';
import request from "@/utils/request";
import { listSystemDict } from '@/api/system/SystemDict'

export default {
  name: "Testpoint",
  dicts: ['sys_normal_disablev'],
  components: { Treeselect, Splitpanes, Pane, PlatformHeader },
  data() {
    return {
      // 遮罩层
      loadingone: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 监测点表格数据
      testpointList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 所有部门树选项
      deptOptions: undefined,
      // 过滤后的部门树选项
      enabledDeptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      importdata: {
        year: null
      },
      orgOptions: [], // 存储机构选项 {value: deptId, label: deptName}
      currentOrgName: '', // 当前选中的机构名称
      // 年份选项
      yearOptions: [],
      sampleTypeOptions: [
        {label: '乡村幼儿', value: '乡村幼儿' },
        {label: '城镇非体力劳动者', value: '城镇非体力劳动者'},
        {label: '城镇幼儿', value: '城镇幼儿'},
        {label: '城镇体力劳动者', value: '城镇体力劳动者'},
        {label: '乡村老人', value: '乡村老人'},
        {label: '城镇老人', value: '城镇老人'},
        {label: '农民', value: '农民'},
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        year: null,
        orgId: 1,
        gps: null,
        contactPerson: null,
        contactTel: null,
        type: null,
        sampleType: [],
        sampleCount: null,
        isPrevious: null,
        isCheck: null,
        isCheckRetest: null,
        address: null,
        enable: null,
        bookingDate: [],
        bookingTime: null,
        dateType: null,
        organizationcode: null
      },
      // 查询参数
      queryUrlParams: {
        pageNum: 1,
        pageSize: 10,
        value: null,
        label: 'video',
        type: 'url',
        description: null,
        sort: null,
        status: null
      },
      // 表单参数
      form: {
        year: new Date().getFullYear().toString(), // 默认填充当前年
        sampleType: [],
        dateType: '1', // '1' = 星期, '0' = 日期
        bookingDate: [], // 存储选中的星期/日期
        enable: '1', // 是否支付宝小程序预约默认为是 ('1' = 是)
        type: '1', // 是否为国测点默认为是 ('1' = 是)
        isPrevious: '0' // 是否为上一年度监测点默认为否 ('0' = 否)
      },
      weekDays: [
        { label: '周一', value: '1' },
        { label: '周二', value: '2' },
        { label: '周三', value: '3' },
        { label: '周四', value: '4' },
        { label: '周五', value: '5' },
        { label: '周六', value: '6' },
        { label: '周日', value: '7' },
      ],
      monthDays: Array.from({ length: 31 }, (_, i) => i + 1), // 1-31 号
      // 表单校验
      rules: {
        year: [
          { required: true, message: "测试年份不能为空", trigger: "blur" }
        ],
        orgId: [
          { required: true, message: "请选择机构名称", trigger: "change" }
        ],
        contactPerson: [
          { required: true, message: "请输入联系人", trigger: "blur" }
        ],
        contactTel: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        sampleCount: [
          { required: true, message: "请输入样本量", trigger: "blur" },
          { pattern: /^\d+$/, message: "样本量必须为数字", trigger: "blur" }
        ],
        gps: [
          { required: true, message: "请输入GPS坐标", trigger: "blur" },
          { pattern: /^[\d°′″,.;\s]+$/, message: "请输入有效的GPS坐标", trigger: "blur" }
        ],
        address: [
          { required: true, message: "请输入具体地址", trigger: "blur" }
        ],
        enable: [
          { required: true, message: "请选择是否支付宝小程序预约", trigger: "change" }
        ],
        dateType: [
          { required: true, message: "请选择预约时间类型", trigger: "change" }
        ],
        bookingDate: [
          { required: true, message: "请选择预约日期", trigger: "change" },
          { validator: (rule, value, callback) => {
              if (!value || value.length === 0) {
                callback(new Error("请至少选择一个预约日期"));
              } else {
                callback();
              }
            }, trigger: 'change' }
        ],
        bookingTime: [
          { required: true, message: "请输入预约时间", trigger: "blur" }
        ],
        sampleType: [
          { required: true, message: "请选择抽样人群类型", trigger: "change" },
          { validator: (rule, value, callback) => {
              if (!value || value.length === 0) {
                callback(new Error("请至少选择一种抽样人群类型"));
              } else {
                callback();
              }
            }, trigger: 'change' }
        ],
        type: [
          { required: true, message: "请选择是否为国测点", trigger: "change" }
        ],
        isPrevious: [
          { required: true, message: "请选择是否为上一年度监测点", trigger: "change" }
        ]
      },
      // 一下为视频监控部分
      clientsArr: [],
      loading: false,
      ws: null,
      adminId: "admin",
      token: "admin-demo-token",
      viewingClient: null, // 当前正在查看的设备ID
      viewingClientName: null,// 设备名称
      // 视频查看相关状态
      videoDialogVisible: false,
      pc: null, // RTCPeerConnection
      stopping: false,
      hasVideo: false,
      stream: null,
      user: {
        userName: '',
        password: '',
        phonenumber: '',
        email: '',
        dept: {},
        createTime: ''
      },
      wsUrl: '',
      // 音频控制相关
      isMuted: false,
      volume: 100,
    };
  },
  created() {
    this.queryParams.year = new Date().getFullYear().toString(); // 默认当前年
    this.getyearsList(100);
    this.getList();
    this.getDeptTree();
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  async mounted() {
    await this.getVideoUrl()
    await this.getUser();
    await this.initWebSocket();
    await this.fetchOnline();
  },
  methods: {
    async getVideoUrl() {
      const data = await listSystemDict(this.queryUrlParams)
      this.wsUrl = data.rows[0].value
    },
    async getUser() {
      try {
        const response = await getUserProfile();
        this.user = response.data;
      } catch (error) {
        console.error("获取用户信息失败:", error);
      }
    },
    // 切换静音
    toggleMute() {
      const video = this.$refs.remoteVideo
      if (video) {
        video.muted = !video.muted
        this.isMuted = video.muted
        console.log('静音状态:', this.isMuted)
      }
    },

    // 调整音量
    changeVolume(value) {
      const video = this.$refs.remoteVideo
      if (video) {
        video.volume = value / 100
        console.log('音量设置:', value)
      }
    },

    // 手动播放
    togglePlay() {
      const video = this.$refs.remoteVideo
      if (video) {
        if (video.paused) {
          video.play().then(() => {
            console.log('手动播放成功')
          }).catch(e => {
            console.error('手动播放失败:', e)
          })
        } else {
          video.pause()
        }
      }
    },
    initWebSocket() {
      this.ws = new WebSocket(this.wsUrl);

      this.ws.onopen = () => {
        console.log('WebSocket连接已建立');
        this.ws.send(JSON.stringify({
          type: 'register',
          clientId: this.adminId,
          role: 'admin',
          token: this.token,
          appUser: this.user.userName,
          appPassword: this.user.password
        }));
      };

      this.ws.onmessage = async (ev) => {
        try {
          const msg = JSON.parse(ev.data);
          // console.log('收到WebSocket消息:', msg);

          if (msg.type === 'online-clients') {
            // console.log('在线设备列表:', msg.clients)
            // 自动更新在线设备列表
            this.clientsArr = msg.clients
            // console.log('在线设备列表---:', this.clientsArr, this.queryParams.organizationcode)
            this.loading = false;
            if (this.queryParams.orgId === 1 || this.queryParams.orgId === 100) {
              this.loadingone = false
              this.testpointList = this.clientsArr
            } else {
              if (this.queryParams.organizationcode.length === 2 && this.clientsArr.length > 0) {
                this.testpointList = this.clientsArr.filter(client =>
                  client.clientId.startsWith(this.queryParams.organizationcode)
                )
              }
              if (this.testpointList.length > 0) {
                // 如果在线设备列表为空，所有监测点都设为离线
                if (this.clientsArr.length < 1) {
                  this.testpointList.forEach(point => point.type = '1');
                } else {
                  // 使用Set提高性能
                  const onlineClientSet = new Set(this.clientsArr.map(client => client.clientId));

                  this.testpointList.forEach(point => {
                    point.type = onlineClientSet.has(point.organizationcode) ? '100' : '1';
                  });
                }

                // console.log('处理后的监测点列表:', this.testpointList);
              }
            }
          } else if (msg.type === 'register-success') {
            // console.log('管理员注册成功');
          } else if (msg.type === 'offer') {
            await this.handleOffer(msg);
          } else if (msg.type === 'candidate') {
            await this.handleIceCandidate(msg);
          } else if (msg.type === 'control' && msg.action === 'stop-view') {
            this.handleRemoteStop();
          } else if (msg.type === 'error') {
            console.error('收到错误消息:', msg);
            this.$message.error('操作失败: ' + msg.message);
          }
        } catch (error) {
          console.error('消息解析错误:', error);
        }
      };

      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error);
        this.loading = false;
      };

      this.ws.onclose = () => {
        console.log('WebSocket连接关闭');
      };
    },
    async view(clientId, type, name) {
      if (type === '1') return this.$message.info('请选择在线机构进行查看！');
      if (this.viewingClient === clientId) {
        return;
      }
      // 1. 设置状态，准备弹窗
      this.viewingClient = clientId;
      this.viewingClientName = name
      this.closePeerConnection(); // 确保清理
      this.videoDialogVisible = true; // 开启弹窗
      // ⚠️ 重点：不再在这里发送 'start-view' 指令！
      this.$message.info('正在开启视频弹窗...');
    },

    onVideoDialogOpen() {
      // 2. 弹窗内容完全渲染后执行此方法
      // console.log('el-dialog 已完全打开，现在尝试获取 remoteVideo...');
      const remoteVideo = this.$refs.remoteVideo;

      // 可以在这里再次检查 $refs.remoteVideo 是否存在
      if (!remoteVideo) {
        console.error('弹窗打开后仍未获取到 remoteVideo 引用！');
        this.$message.error('视频播放元素未就绪');
        return;
      }

      console.log('✅ 成功获取到 remoteVideo:');

      // 3. 在这里发送 'start-view' 指令，启动 WebRTC 流程
      if (this.ws && this.ws.readyState === WebSocket.OPEN && this.viewingClient) {
        this.ws.send(JSON.stringify({
          type: 'control',
          action: 'start-view',
          target: this.viewingClient,
          requester: this.adminId
        }));
        // console.log('发送查看指令给:', this.viewingClient);
        this.$message.info('正在连接摄像头...');
      } else {
        this.$message.error('WebSocket 未连接或设备ID丢失');
        this.handleVideoClose();
      }
    },

    async handleOffer(msg) {
      try {
        console.log('收到Offer，开始建立音视频连接')

        // 如果已经存在连接，先关闭
        if (this.pc) {
          this.closePeerConnection()
        }

        // 创建新的 PeerConnection
        this.pc = new RTCPeerConnection({
          iceServers: [
            { urls: 'stun:stun.l.google.com:19302' },
            { urls: 'stun:stun1.l.google.com:19302' },
            { urls: 'stun:stun2.l.google.com:19302' },
            { urls: 'stun:stun.qq.com:3478' },
            // TURN服务器
            {
              urls: [
                'turn:106.39.1.69:3478?transport=udp',
                'turn:106.39.1.69:3478?transport=tcp'
              ],
              username: 'dengfeng1992',
              credential: 'wu583392333@qq.com'
            }
          ],
          iceTransportPolicy: 'all', // 允许所有类型的连接
          sdpSemantics: 'unified-plan'
        })

        // 设置音视频流回调
        this.pc.ontrack = (ev) => {
          console.log('收到音视频流，轨道数量:', ev.streams.length)
          if (ev.streams && ev.streams[0]) {
            this.stream = ev.streams[0]
            /*console.log('音视频流信息:', {
              videoTracks: this.stream.getVideoTracks().length,
              audioTracks: this.stream.getAudioTracks().length,
              active: this.stream.active
            })*/

            // 检查音频轨道
            const audioTracks = this.stream.getAudioTracks()
            if (audioTracks.length > 0) {
              /*console.log('音频轨道详情:', {
                label: audioTracks[0].label,
                enabled: audioTracks[0].enabled,
                muted: audioTracks[0].muted,
                readyState: audioTracks[0].readyState
              })*/
            }

            this.$nextTick(() => {
              const remoteVideo = this.$refs.remoteVideo
              // console.log('remoteVideo----------', remoteVideo, this.stream)
              if (remoteVideo) {
                remoteVideo.srcObject = this.stream
                this.hasVideo = true

                // 设置音频属性
                remoteVideo.muted = false // 确保不静音
                remoteVideo.volume = 1.0  // 最大音量

                console.log('音视频元素srcObject已设置')

                // 添加事件监听器来调试音视频状态
                remoteVideo.onloadedmetadata = () => {
                  console.log('音视频元数据加载完成')
                  // console.log('视频分辨率:', remoteVideo.videoWidth + 'x' + remoteVideo.videoHeight)
                  this.$message.success('音视频连接建立成功')
                }

                remoteVideo.oncanplay = () => {
                  console.log('音视频可以播放')
                  // 尝试播放
                  remoteVideo.play().catch(e => {
                    console.error('自动播放失败:', e)
                    // 如果自动播放失败，显示提示让用户手动播放
                    this.$message.warning('请点击视频区域手动播放音视频')
                  })
                }

                remoteVideo.onplay = () => {
                  console.log('音视频开始播放')
                }

                remoteVideo.onerror = (e) => {
                  console.error('音视频播放错误:', e)
                }

                // 添加音频相关事件
                remoteVideo.onvolumechange = () => {
                  console.log('音量改变:', remoteVideo.volume)
                }
              }
            })
          }
        }

        this.pc.oniceconnectionstatechange = () => {
          // console.log('ICE连接状态:', this.pc.iceConnectionState)
          switch (this.pc.iceConnectionState) {
            case 'connected':
              console.log('ICE连接已建立')
              break
            case 'disconnected':
            case 'failed':
              this.$message.warning('音视频连接已断开')
              this.hasVideo = false
              break
          }
        }

        this.pc.onicecandidate = (e) => {
          if (e.candidate) {
            console.log('生成ICE候选:', e.candidate)
            if (this.ws && this.ws.readyState === WebSocket.OPEN) {
              this.ws.send(JSON.stringify({
                type: "candidate",
                target: this.viewingClient,
                candidate: e.candidate
              }))
            }
          } else {
            console.log('ICE候选收集完成')
          }
        }

        // 处理 offer
        const desc = new RTCSessionDescription({ type: "offer", sdp: msg.sdp })
        await this.pc.setRemoteDescription(desc)
        console.log('Remote description 设置成功')

        // 创建并发送 answer
        const answer = await this.pc.createAnswer()
        await this.pc.setLocalDescription(answer)

        this.ws.send(JSON.stringify({
          type: "answer",
          target: this.viewingClient,
          sdp: answer.sdp
        }))

        console.log('Answer 发送成功')

      } catch (error) {
        console.error('处理Offer失败:', error)
        this.$message.error('建立音视频连接失败: ' + error.message)
        this.closePeerConnection()
        this.videoDialogVisible = false
        this.viewingClient = null
      }
    },

    async handleIceCandidate(msg) {
      if (!this.pc) {
        console.error('PeerConnection未初始化');
        return;
      }

      try {
        await this.pc.addIceCandidate(new RTCIceCandidate(msg.candidate));
        console.log('✅ ICE候选添加成功');
      } catch (error) {
        console.error('❌ 添加ICE候选失败:', error);
      }
    },

    async stopView() {
      this.stopping = true;
      try {
        // 发送停止查看指令
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
          this.ws.send(JSON.stringify({
            type: 'stop-view',
            targetClientId: this.viewingClient
          }));
        }

        // 关闭本地连接
        this.closePeerConnection();

        this.videoDialogVisible = false;
        this.viewingClient = null;
        this.$message.success('已关闭摄像头查看');
      } catch (error) {
        console.error('关闭查看失败:', error);
        this.$message.error('关闭查看失败');
      } finally {
        this.stopping = false;
      }
    },

    handleRemoteStop() {
      console.log('收到设备端停止指令')
      this.$message.info('设备端已停止视频流');
      this.closePeerConnection();
      this.videoDialogVisible = false;
      this.viewingClient = null;
      this.viewingClientName = null;
    },

    handleVideoClose() {
      this.stopView();
    },

    closePeerConnection() {
      if (this.pc) {
        this.pc.close();
        this.pc = null;
      }
      if (this.stream) {
        this.stream.getTracks().forEach(track => track.stop());
        this.stream = null;
      }
      this.hasVideo = false;

      const remoteVideo = this.$refs.remoteVideo;
      if (remoteVideo) {
        remoteVideo.srcObject = null;
      }
    },

    takeSnapshot() {
      const video = this.$refs.remoteVideo;
      if (!video || !video.videoWidth) {
        this.$message.warning('当前没有视频流');
        return;
      }

      const canvas = document.createElement('canvas');
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(video, 0, 0);

      const link = document.createElement('a');
      link.download = `snapshot-${new Date().getTime()}.png`;
      link.href = canvas.toDataURL();
      link.click();

      this.$message.success('截图已保存');
    },

    toggleFullscreen() {
      const video = this.$refs.remoteVideo;
      if (!document.fullscreenElement) {
        if (video.requestFullscreen) {
          video.requestFullscreen();
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        }
      }
    },

    cleanup() {
      this.closePeerConnection();
      if (this.ws) {
        this.ws.close();
      }
    },
    handleDateTypeChange(val) {
      // 切换时间类型时清空已选日期
      this.form.bookingDate = [];
    },
    getyearsList(id) {
      const getyearsdata = {
        orgId: id
      }
      getyears(getyearsdata).then(response => {
        this.yearOptions = response
        const currentYear = new Date().getFullYear().toString();
        if (!this.yearOptions.includes(currentYear)) {
          this.yearOptions.unshift(currentYear);
        }
      });
    },
    /** 查询监测点列表 */
    getList() {
      // console.log('获取监测点列表', this.queryParams)
      // console.log('----------', this.clientsArr)
      this.loadingone = true;
      if (this.queryParams.orgId === 1 || this.queryParams.orgId === 100) {
        this.loadingone = false
        this.testpointList = this.clientsArr
      } else {
        listTestpoint(this.queryParams).then(response => {
          this.testpointList = response.rows;
          if (this.testpointList <= 0 && this.queryParams.organizationcode.length === 2 && this.clientsArr.length > 0) {
            this.testpointList = this.clientsArr.filter(client =>
              client.clientId.startsWith(this.queryParams.organizationcode)
            )
          } else {
            if (this.clientsArr.length > 0 && this.testpointList.length > 0) {
              // 使用Set提高查找性能
              const onlineClientSet = new Set(this.clientsArr.map(client => client.clientId));

              this.testpointList.forEach(point => {
                point.type = onlineClientSet.has(point.organizationcode) ? '100' : '1';
              });
            }
            if( this.testpointList.length > 0 && this.clientsArr.length < 1) {
              this.testpointList.forEach(point => {
                point.type = '1';
              });
            }
          }
          this.total = response.total;
          this.loadingone = false;
        });
      }
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        // 过滤掉 type 为 "1" 的节点
        const filterType1Nodes = (nodes) => {
          return nodes.filter(node => {
            // 如果当前节点的 type 为 "1"，则过滤掉
            if (node.type === "1") {
              return false;
            }
            // 递归处理子节点
            if (node.children && node.children.length) {
              node.children = filterType1Nodes(node.children);
            }
            return true;
          });
        };
        // 应用过滤
        this.deptOptions = filterType1Nodes(response.data);
        this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(this.deptOptions)));
      });
    },
    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false;
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children);
        }
        return true;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.orgId = data.id;
      this.handleQuery();
      this.getyearsList(data.id)
      this.orgOptions = [];
      this.form.orgId = null;
      this.currentOrgName = '';
      this.queryParams.organizationcode = data.organizationcode
      getOrg(data.id).then(response => {
        if (response.code === 200 && response.data.length > 0) {
          // 填充机构选项
          this.orgOptions = response.data.map(org => ({
            value: org.deptId,
            label: org.deptName,
          }));
          // 默认选中第一个机构
          if (this.orgOptions.length > 0) {
            this.form.orgId = this.orgOptions[0].value;
            this.currentOrgName = this.orgOptions[0].label;
          } else {
            // 无机构时清空数据
            this.orgOptions = [];
            this.form.orgId = null;
            this.currentOrgName = '';
          }
        }
      })
    },
    handleOrgChange(val) {
      const selectedOrg = this.orgOptions.find(item => item.value === val);
      this.currentOrgName = selectedOrg ? selectedOrg.label : '';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        year: new Date().getFullYear().toString(), // 默认当前年
        orgId: null,
        gps: null,
        contactPerson: null,
        contactTel: null,
        type: '1', // 是否为国测点默认为是
        sampleType: [], // 抽样人群类型（数组）
        sampleCount: null,
        isPrevious: '0', // 是否为上一年度监测点默认为否
        isCheck: null,
        isCheckRetest: null,
        address: null,
        enable: '1', // 是否支付宝小程序预约默认为是
        bookingDate: [], // 预约日期（数组）
        bookingTime: null,
        dateType: '1', // 预约时间类型默认为星期
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // 检查机构列表是否为空
      if (this.orgOptions.length === 0) {
        this.$message.warning("当前节点无关联机构，无法新增监测点！");
        return; // 直接返回，不打开弹窗
      }

      // 机构列表不为空，正常打开新增弹窗
      this.reset();
      this.open = true;
      this.title = "新增";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 备份原始数组
          const originalBookingDate = [...this.form.bookingDate];
          const originalSampleType = [...this.form.sampleType];
          this.form.sampleType = this.form.sampleType.join(',')
          this.form.bookingDate = this.form.bookingDate.join(',')

          const submitAction = this.form.id != null
            ? updateTestpoint(this.form)
            : addTestpoint(this.form);
          submitAction.then(response => {
            this.$modal.msgSuccess(this.form.id != null ? "修改成功" : "新增成功");
            this.open = false;
            this.getList();
          }).catch(error => {
            // 提交失败时恢复数组形式
            this.form.bookingDate = originalBookingDate;
            this.form.sampleType = originalSampleType;
            console.error("提交失败:", error);
          });
        }
      });
    },
    /** 删除按钮操作 */
    // handleDelete(row) {
    //   const ids = row.id || this.ids;
    //   this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？', {
    //     customClass: 'custom-confirm' // 添加自定义类名
    //   }).then(function () {
    //     return delTestpoint(ids);
    //   }).then(() => {
    //     this.getList();
    //     this.$modal.msgSuccess("删除成功");
    //   }).catch(() => {
    //   });
    // },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除编号为"' + ids + '"的数据项？', '提示',{
        /* title: '确认',
        message: '是否确认删除编号为"' + ids + '"的数据项？',
        customClass: 'custom-confirm' // 添加自定义类名 */
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'custom-confirm', // 添加自定义类名
      }).then(function () {
        return delTestpoint(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('monitormanage/testpoint/export', {
        ...this.queryParams
      }, `testpoint_${new Date().getTime()}.xlsx`)
    },
    /** 导入上一年度监测点按钮操作 */
    async handleImport() {
      this.importdata = {
        year: new Date().getFullYear().toString(),
      };
      importold(this.importdata).then(response => {
        if(response.code === 200){
          this.$modal.msgSuccess("导入成功");
          this.getList();
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  overflow: hidden;
  background: url('../../assets/images/bgn.png');
  background-size: 100% 100%;
  padding: 16px;
  box-sizing: border-box;
  padding-top: 0;

  .el-row {
    .splitpanes {
      height: 100%;

      .left-pane {
        background: transparent;
        border-radius: 8px;
        padding: 15px;

        .dept-search {
          margin-bottom: 20px;
        }

        .tree-container {
          height: calc(100% - 60px);
          overflow-y: auto;
        }
      }

      .right-pane {
        background: transparent;
        border-radius: 8px;
        padding: 15px;
        padding-left: 0;
        padding-right: 45px;
        margin-left: 15px !important;

        .search-form {
          margin-bottom: 0px;
        }

        .action-bar {
          margin-bottom: 15px;
        }
      }
    }
  }
}

// 表格相关样式
::v-deep .el-table {
  background: transparent;
  border-radius: 12px;
  overflow: hidden;

  .el-table__header-wrapper {
    border-radius: 12px;
    overflow: hidden;

    th:first-child {
      border-top-left-radius: 12px;
    }
    th:last-child {
      border-top-right-radius: 12px;
    }
  }

  .el-table__body-wrapper {
    border-radius: 0 0 12px 12px;

    tr {
      td:first-child {
        border-bottom-left-radius: 12px;
      }
      td:last-child {
        border-bottom-right-radius: 12px;
      }
    }

    tr.el-table__row {
      td:first-child {
        border-top-left-radius: 12px;
        border-bottom-left-radius: 12px;
      }
      td:last-child {
        border-top-right-radius: 12px;
        border-bottom-right-radius: 12px;
      }
    }
  }
}

::v-deep .el-table th.el-table__cell {
  border: none;
}

.el-table::before {
  height: 0;
}

::v-deep .el-table th.el-table__cell.is-leaf {
  border-bottom: none;
}

::v-deep .el-table th {
  background: #f7e797;
  color: #1e4f91;
  font-weight: bold;
  font-size: 18px;
  height: 30px;
  line-height: 30px;
}

::v-deep .el-table__row {
  td {
    border: none;
  }
}

::v-deep .el-table__row:nth-child(odd) {
  background: linear-gradient(90deg, #99e8ff, #4f85ff);
}

::v-deep .el-table__row:nth-child(even) {
  background: linear-gradient(90deg, #4f85ff, #99e8ff);
}

::v-deep .el-table td {
  color: #000;
  font-size: 18px;
  padding: 12px 8px;
}

::v-deep .el-table__body {
  border-collapse: separate !important;
  border-spacing: 0 5px !important;
}

::v-deep .el-table__body tr:hover > td {
  background: #9ef7c5 !important;
}

::v-deep .el-table .el-button--mini {
  color: #000 !important;
  font-size: 18px;
  font-weight: 400;
}

::v-deep .el-table .cell {
  line-height: 35px;
  height: 35px;
}

// 分页样式
::v-deep .pagination {
  margin-top: 16px;
  padding: 10px 0;
  background-color: #f8fbff;
  border-radius: 8px;
}

::v-deep .pagination-container {
  background: transparent;
}

::v-deep .el-pagination {
  color: #fff !important;
}

::v-deep .el-pagination__total {
  color: #fff !important;
}

::v-deep .el-pagination__jump {
  color: #fff !important;
}

// 输入框样式
::v-deep .el-input .el-input__inner {
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid #00CCFE;
  border-radius: 6px;
  color: #f0f0f0;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
  font-size: 16px;
}

::v-deep .el-input__inner::placeholder {
  color: #fff !important;
}

::v-deep .el-input .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.6);
  background-color: rgba(255, 255, 255, 0.15);
  color: #fff;
}

::v-deep .el-input__clear {
  color: #a8c0ff;
}

::v-deep .el-input__clear:hover {
  color: #409eff;
}

// 表单按钮样式
::v-deep .el-form-item .el-button {
  border-radius: 22px;
  font-weight: 600;
  font-size: 16px;
  padding: 10px 28px;
  transition: all 0.3s ease;
  box-shadow: 0 3px 8px rgba(66, 133, 244, 0.3);
}

.el-button {
  font-size: 14px;
  padding: 10px 20px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.25s ease;
}

::v-deep .el-form-item .action-btn {
  border-radius: 20px;
  font-weight: 600;
  border: none;
  transition: all 0.3s ease;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);
}

::v-deep .el-form-item .action-btn:hover {
  transform: translateY(-2px);
}

// 按钮颜色渐变
::v-deep .el-form-item .search-btn {
  background: linear-gradient(135deg, #b4cdeb, #2f6bcc);
  color: #fff;
}

::v-deep .el-form-item .search-btn:hover {
  background: linear-gradient(135deg, #5aa2f8, #3a8ef6);
  box-shadow: 0 6px 14px rgba(58, 142, 246, 0.5);
}

::v-deep .el-form-item .reset-btn {
  background: linear-gradient(135deg, #df9f3f, #edc73d);
  color: #fff;
}

::v-deep .el-form-item .reset-btn:hover {
  background: linear-gradient(135deg, #ffcc80, #ffb74d);
  box-shadow: 0 6px 14px rgba(255, 183, 77, 0.5);
}

::v-deep .el-form-item .add-btn {
  background: linear-gradient(135deg, #4fd1c5, #38b2ac);
  color: #fff;
}

::v-deep .el-form-item .add-btn:hover {
  background: linear-gradient(135deg, #6ee7df, #4fd1c5);
  box-shadow: 0 6px 14px rgba(72, 187, 176, 0.5);
}

::v-deep .el-form-item .edit-btn {
  background: linear-gradient(135deg, #8bc34a, #6fa33f);
  color: #fff;
}

::v-deep .el-form-item .edit-btn:hover {
  background: linear-gradient(135deg, #a8d672, #8bc34a);
  box-shadow: 0 6px 14px rgba(139, 195, 74, 0.5);
}

::v-deep .el-form-item .delete-btn {
  background: linear-gradient(135deg, #e57373, #c62828);
  color: #fff;
}

::v-deep .el-form-item .delete-btn:hover {
  background: linear-gradient(135deg, #ef9a9a, #e57373);
  box-shadow: 0 6px 14px rgba(229, 115, 115, 0.5);
}

::v-deep .el-form-item .import-btn {
  background: linear-gradient(135deg, #9c27b0, #7b1fa2);
  color: #fff !important;
}

::v-deep .el-form-item .import-btn:hover {
  background: linear-gradient(135deg, #ba68c8, #9c27b0);
  box-shadow: 0 6px 14px rgba(156, 39, 176, 0.5);
}

::v-deep .el-form-item .export-btn {
  background: linear-gradient(135deg, #1ec2e7, #54a9ff);
  color: #fff;
}

::v-deep .el-form-item .export-btn:hover {
  background: linear-gradient(135deg, #7cdde7, #2989e9);
  box-shadow: 0 6px 14px rgba(160, 180, 200, 0.5);
}

// 树结构样式
::v-deep .el-tree {
  background: #0080FF;
  color: #fff;
  border-radius: 8px;
}

::v-deep .el-tree-node__content:hover {
  background-color: #0879e9;
}

::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #0879e9;
}

// 对话框按钮样式
.dialog-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;

  .el-button {
    min-width: 120px;
    height: 40px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
    letter-spacing: 1px;
    transition: all 0.3s;
    margin: 0;
  }
  .dialog-cancel-btn {
    border: none;
    background: linear-gradient(135deg, #aed7ff, #80bcf9);
    color: #fff;
    font-size: 16px;
    box-shadow: 0 6px 14px rgb(128 188 249 / 50%);
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }

  .dialog-confirm-btn {
    background: linear-gradient(90deg, #4f85ff, #6a8cff);
    border: none;
    color: #fff;
    font-size: 16px;
    box-shadow: 0 6px 14px rgb(128 188 249 / 50%);
    &:hover {
      background: linear-gradient(90deg, #3a73ff, #4f85ff);
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(79, 133, 255, 0.3);
    }

    &:active {
      transform: translateY(0);
    }

  }
  .add-btn {
    background: linear-gradient(135deg, #4fd1c5, #38b2ac);
    color: #fff;
    &:hover {

      transform: translateY(-2px);
      background: linear-gradient(135deg, #6ee7df, #4fd1c5);
      box-shadow: 0 6px 14px rgba(72, 187, 176, 0.5);
    }

    &:active {
      transform: translateY(0);
    }
  }



  .edit-btn {
    background: linear-gradient(135deg, #8bc34a, #6fa33f);
    color: #fff;
    &:hover {

      transform: translateY(-2px);
      background: linear-gradient(135deg, #a8d672, #8bc34a);
      box-shadow: 0 6px 14px rgba(139, 195, 74, 0.5);
    }

    &:active {
      transform: translateY(0);
    }
  }


}

// 对话框样式 - 修复了v-deep问题
::v-deep {
  .custom-dialog {
    border-radius: 16px !important;
    overflow: hidden!important;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2)!important;
    background: linear-gradient(145deg, #f5f7fa, #e4e8f0)!important;

    .el-dialog__header {
      background: linear-gradient(90deg, #8caefb, #0160FA)!important;
      padding: 20px!important;
      margin: 0!important;
      border-bottom: none!important;

      .el-dialog__title {
        color: #fff!important;
        font-size: 20px!important;
        font-weight: 600!important;
        letter-spacing: 1px!important;
      }

      .el-dialog__headerbtn {
        top: 20px!important;
        right: 20px!important;

        .el-dialog__close {
          color: #fff!important;
          font-size: 20px!important;
        }
      }
    }

    .el-dialog__body {
      padding: 0px!important;
      background: linear-gradient(145deg, #e6f0ff, #bad2ff)!important;
      color: #333!important;
    }

    .el-dialog__footer {
      padding: 20px 40px!important;
      background: linear-gradient(145deg, #e6f0ff, #a2c3ff)!important;
      border-top: 1px solid rgba(79, 133, 255, 0.1)!important;
      border-radius: 0 0 16px 16px!important;
    }
  }

  .custom-dialog .el-input__inner,
  .custom-dialog .el-select .el-input__inner {
    color: #000 !important;
    border: 1px solid rgba(79, 133, 255, 0.3)!important;
  }

  .custom-dialog .el-input__inner:focus {
    border-color: #409eff !important;
    box-shadow: 0 0 5px rgba(64, 158, 255, 0.6) !important;
    background-color: rgba(255, 255, 255, 0.15) !important;
  }

  .custom-dialog .el-input__inner::placeholder {
    color: #555 !important;
    font-size: 14px!important;
  }
}

// 滚动条样式
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  border-radius: 4px;
  background-color: rgb(1 96 250);
}

::-webkit-scrollbar-thumb {
  border-radius: 8px;
  background-color: #0080ff;
}

::-webkit-scrollbar-thumb:hover {
  background-color: #C7C9CC;
}

// 其他样式
::v-deep .splitpanes.default-theme .splitpanes__pane {
  background-color: transparent !important;
}

::v-deep .splitpanes.default-theme .splitpanes__splitter {
  background-color: transparent !important;
  border: none !important;
}

::v-deep .custom-form .el-input__inner {
  height: 36px !important;
  line-height: 36px !important;
}

::v-deep .custom-height-input .el-input__inner {
  height: 36px;
  line-height: 36px;
}

::v-deep .el-switch.is-checked .el-switch__core {
  border-color: #0160FA;
  background-color: #0160FA;
}
::v-deep .el-form-item__label {
  color: #000!important;
}
// 响应式调整
@media (max-width: 768px) {
  ::v-deep .custom-dialog {
    width: 90% !important;

    .el-dialog__body {
      padding: 20px;
    }

    .el-form-item {
      margin-bottom: 18px;
    }

    .el-col {
      width: 100%;
    }
  }
}
::v-deep .el-tree-node:focus > .el-tree-node__content {
  background-color: transparent;
}
.video-container {
  width: 100%;
  text-align: center;
  padding: 10px;
}

.video-element {
  width: 100%;
  max-width: 1200px;
  height: 675px; /* 1200x675 是16:9比例 */
  object-fit: contain;
}

::v-deep .el-tag{
  padding: 0px 16px;
  letter-spacing: 4px;
}
.audio-controls {
  position: absolute;
  bottom: 20px;
  left: 20px;
  display: flex;
  align-items: center;
  background: rgba(0, 0, 0, 0.7);
  padding: 10px;
  border-radius: 20px;
  z-index: 10;
}

.audio-btn {
  color: white;
  border: none;
}

.volume-slider {
  .el-slider__runway {
    background-color: #666;
  }
  .el-slider__bar {
    background-color: #409EFF;
  }
  .el-slider__button {
    border-color: #409EFF;
  }
}

.video-container {
  position: relative;
  width: 100%;
  text-align: center;
  padding: 10px;
}
</style>

<style lang="scss">
.select-dropdown {
  background-color: #d4e4ff !important;
  border: 1px solid rgba(79, 133, 255, 0.3) !important;

  .el-select-dropdown__item {
    color: #000 !important;
  }

  .el-select-dropdown__item.hover,
  .el-select-dropdown__item:hover {
    background-color: rgba(255, 255, 255, 0.2) !important;
  }

  .el-select-dropdown__item.selected {
    background-color: rgba(64, 158, 255, 0.5) !important;
  }
}
</style>
